/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.evaluation;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.evaluation.prepare.EvaluationToolsDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationToolsRepository;
import cn.ac.nercis.pes.repository.dal.knowledge.KmEvaluationToolsRepository;
import cn.ac.nercis.pes.repository.mapper.evaluation.EvaluationToolsMapper;
import cn.ac.nercis.pes.repository.model.evaluation.EvaluationToolsDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 测评工具信息服务类
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class EvaluationToolsService {
    private final static String KM_ORDER_FIELD = "sort";

    private final KmEvaluationToolsRepository kmEvaluationToolsRepository;
    private final EvaluationToolsRepository evaluationToolsRepository;

    @Autowired
    public EvaluationToolsService(KmEvaluationToolsRepository kmEvaluationToolsRepository, EvaluationToolsRepository evaluationToolsRepository) {
        this.kmEvaluationToolsRepository = kmEvaluationToolsRepository;
        this.evaluationToolsRepository = evaluationToolsRepository;
    }

    public List<EvaluationToolsDTO> findEvaluationTools(String systemId){
        List<EvaluationToolsDO> evaluationTools = this.evaluationToolsRepository.findAllBySystemId(systemId);
        if(CollectionUtils.isEmpty(evaluationTools)){
            this.generateDefaultTools(systemId);
            evaluationTools = this.evaluationToolsRepository.findAllBySystemId(systemId);
        }
        return evaluationTools.stream()
                .map(EvaluationToolsMapper.INSTANCE::toToolsDTO)
                .collect(Collectors.toList());
    }

    public Result<EvaluationToolsDTO> saveEvaluationTools(EvaluationToolsDTO evaluationTools){
        if(StringUtils.isEmpty(evaluationTools.getName())){
            evaluationTools.setName("");
        }
        if(StringUtils.isEmpty(evaluationTools.getVersion())){
            evaluationTools.setVersion("");
        }
        if(StringUtils.isEmpty(evaluationTools.getVendor())){
            evaluationTools.setVendor("");
        }
        try{
            if(StringUtils.isEmpty(evaluationTools.getId())){
                return create(evaluationTools);
            }else{
                return modify(evaluationTools);
            }
        }catch (Exception e){
            log.error("保存测评工具信息出错：",e);
            return Result.failed();
        }
    }

    public Result<String> batchSaveEvaluationTools(List<EvaluationToolsDTO> evaluationTools){
        Result<String> result = Result.success();
        for(EvaluationToolsDTO item : evaluationTools){
            Result<EvaluationToolsDTO> itemResult = saveEvaluationTools(item);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    public Result<String> deleteEvaluationTool(String id){
        try{
            return evaluationToolsRepository.findById(id)
                    .map(toolsDO -> {
                        evaluationToolsRepository.delete(toolsDO);
                        return toolsDO;
                    })
                    .map(EvaluationToolsDO::getId)
                    .map(Result::success)
                    .orElse(Result.failed());
        }catch (Exception ex){
            log.error("删除测评工具信息出错：",ex);
            return Result.failed();
        }
    }

    public Result<String> batchDeleteEvaluationTool(Set<String> ids){
        Result<String> result = Result.success();
        for(String id : ids){
            Result<String> itemResult = deleteEvaluationTool(id);
            if(!itemResult.isSuccess()){
                result = Result.failed(ResultCode.FAIL);
                break;
            }
        }
        return result;
    }

    private Result<EvaluationToolsDTO> create(EvaluationToolsDTO evaluationTools){
        return Optional.of(EvaluationToolsMapper.INSTANCE.toToolsDO(evaluationTools))
                .map(e->{
                    e.setIsCommon(false);
                    e.setSort(getMaxOrder(evaluationTools.getSystemId())+1);
                    e.setCreateTime(LocalDateTime.now());
                    return e;
                })
                .map(evaluationToolsRepository::save)
                .map(EvaluationToolsMapper.INSTANCE::toToolsDTO)
                .map(Result::success)
                .orElse(Result.failed());
    }

    private Result<EvaluationToolsDTO> modify(EvaluationToolsDTO evaluationTools){
        EvaluationToolsDO source = this.evaluationToolsRepository.findById(evaluationTools.getId()).orElse(null);
        if(Objects.isNull(source)){
            return Result.failed(ResultCode.NOT_FOUND);
        }
        return Optional.of(source)
                .map(s->{
                    s.setName(evaluationTools.getName());
                    s.setVersion(evaluationTools.getVersion());
                    s.setVendor(evaluationTools.getVendor());
                    s.setDesc(evaluationTools.getDesc());
                    s.setModifyTime(LocalDateTime.now());
                    return s;
                })
                .map(evaluationToolsRepository::save)
                .map(EvaluationToolsMapper.INSTANCE::toToolsDTO)
                .map(Result::success)
                .orElse(Result.failed(ResultCode.FAIL));
    }

    private Integer getMaxOrder(String systemId){
        return evaluationToolsRepository.findAllBySystemId(systemId)
                .stream()
                .mapToInt(EvaluationToolsDO::getSort)
                .max()
                .orElse(0);
    }

    private void generateDefaultTools(String systemId){
        List<EvaluationToolsDO> defaultTools = this.kmEvaluationToolsRepository.findAll(Sort.by(Sort.Direction.ASC,KM_ORDER_FIELD))
                .stream()
                .map(EvaluationToolsMapper.INSTANCE::toToolsDO)
                .peek(et->{
                    et.setSystemId(systemId);
                    et.setCreateTime(LocalDateTime.now());
                })
                .collect(Collectors.toList());
        this.evaluationToolsRepository.saveAll(defaultTools);
    }
}